package com.ruoyi.system.service.sso;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;

import org.springframework.web.util.UriBuilder;

/**
 * @author PC
 */
public class OkHttpUtils {
    private OkHttpClient okHttpClient = null;
    private HashMap<String, HashMap<String, Cookie>> cookieManager = new HashMap<>();

    private HashMap<String,String> heads = new HashMap<>();


    public OkHttpUtils() {
        // 1. 创建自定义拦截器
        Interceptor uaInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request originalRequest = chain.request();
                // 2. 构建新的请求，添加自定义 UA
                Request modifiedRequest = originalRequest.newBuilder()
                        .header("User-Agent", "IndSvr_HomeLab_SSO/1.0.0") // 替换为你的UA
                        .build();
                return chain.proceed(modifiedRequest);
            }
        };


       this. okHttpClient = new OkHttpClient.Builder()
               .addInterceptor(uaInterceptor) // 添加应用拦截器（优先推荐）
                .cookieJar(new CookieJar() {
                    @Override
                    public void saveFromResponse(@NotNull HttpUrl httpUrl, @NotNull List<Cookie> list) {
                        HashMap<String, Cookie> stringCookieHashMap = cookieManager.get(httpUrl.host());
                        if (stringCookieHashMap==null) {
                            stringCookieHashMap = new HashMap<>();
                        }
                        for (Cookie cookie : list) {
                            stringCookieHashMap.put(cookie.name(),cookie);
                        }
                        cookieManager.put(httpUrl.host(),stringCookieHashMap);
                    }

                    @NotNull
                    @Override
                    public List<Cookie> loadForRequest(@NotNull HttpUrl httpUrl) {
                        List<Cookie> cookies = new ArrayList<>();
                        HashMap<String, Cookie> stringCookieHashMap = cookieManager.get(httpUrl.host());
                        if (stringCookieHashMap!=null) {
                            for (Map.Entry<String, Cookie> stringCookieEntry : stringCookieHashMap.entrySet()) {
                                cookies.add(stringCookieEntry.getValue());
                            }
                        }
                        return cookies;
                    }
                }).build();
    }


    public HashMap<String,String> putHead(String k,String v){
        heads.put(k,v);
        return heads;
    }



    //================================================================

    public String get(String url, HashMap<String,String> query) throws Exception{

        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();

        query.forEach(urlBuilder::addQueryParameter);

        Request.Builder builder = new Request.Builder().url(urlBuilder.build().url());

        heads.forEach(builder::addHeader);

        Request build = builder.build();

        Response execute = okHttpClient.newCall(build).execute();

        return execute.body().string();
    }


    public String postForJson(String url, String json) throws Exception {

        Request.Builder builder = new Request.Builder().url(url);

        heads.forEach(builder::addHeader);

        if (json != null) {
            builder.addHeader("Content-Type", "application/json");
            final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            RequestBody body = FormBody.create(json, JSON);
            builder.post(body);
        }
        Request build = builder.build();

        Response execute = okHttpClient.newCall(build).execute();

        return execute.body().string();
    }


    public String postForForm(String url, HashMap<String,String> body) throws Exception{

        Request.Builder builder = new Request.Builder().url(url);

        heads.forEach(builder::addHeader);

        FormBody.Builder builder1 = new FormBody.Builder();

        body.forEach(builder1::add);

        builder.post(builder1.build());

        Request build = builder.build();

        Response execute = okHttpClient.newCall(build).execute();

        return execute.body().string();
    }


    public Gson getGson (){
        return  new GsonBuilder().serializeNulls().serializeSpecialFloatingPointValues().create();
    }


    public HashMap<String, Cookie> getCookie(String host){
        return cookieManager.get(host);
    }
}
